package com.miyake.dsp.osa.lab.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFileChooser;

import com.miyake.dsp.osa.lab.FileSetting;
import com.miyake.dsp.osa.lab.SettingPanelListener;

public class FileChooserPanelUI extends SettingPanelUI {

	JFileChooser fileChooser;
	protected String[] fileList;
	protected String path;
	protected int currentIndex = 0;
	
	private String showFileChooser() {
		if (fileChooser == null) {
			fileChooser = new JFileChooser();
			
		}
		int selected = fileChooser.showOpenDialog(this);
		if (selected == JFileChooser.APPROVE_OPTION){
			return fileChooser.getSelectedFile().getAbsolutePath();
		}else if (selected == JFileChooser.CANCEL_OPTION){
		}else if (selected == JFileChooser.ERROR_OPTION){
		}
		return null;
	}
	
	@Override
	protected void createCustomComponent(final Object o) {
		JButton button = new JButton("File");
		add(button);
		button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				String filename = showFileChooser();
				File file = new File(path = getFolder(filename));
				fileList = file.list();
			
				if (filename != null) {
					((FileSetting)o).setFilePath(filename);
					fireOnSet();
					removeAll();
					createPanel();
					currentIndex = 0;
				}
			}
			
		});
		
		JButton next = new JButton("Next");
		add(next);
		next.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				currentIndex++;
				changeFile(o);
			}
			
		});
		JButton prev = new JButton("Prev");
		add(prev);
		prev.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				currentIndex--;
				changeFile(o);
			}
			
		});
	}

	protected String getFolder(String filename) {
		String[] s  = filename.split("\\\\");
		String ret = "";
		for (int i = 0; i < s.length-1; i++) {
			ret += s[i] + "\\\\";
		}
		return ret;
	}

	private void changeFile(final Object o) {
		if (fileList != null) {
			if (currentIndex < 0) {
				currentIndex = fileList.length - 1;
			}
			else if (currentIndex > fileList.length-1) {
				currentIndex = 0;
			}
			((FileSetting)o).setFilePath(path + "\\\\" + fileList[currentIndex]);
			fireOnSet();
			removeAll();
			createPanel();
		}
	}

	public FileChooserPanelUI(Object o, SettingPanelListener listener) {
		super(o, listener);
		// TODO Auto-generated constructor stub
	}

}
